import json

from flask.json import jsonify
from flask import request

from app import db
from app.user import user
from app.user.models import User
from app.common.utils import exception_catch, login_require


@user.route('/index', methods=['GET'])
def index():
    return jsonify({'code': 0, 'data': [], 'message': '', 'error': ''})


@user.route('/create', methods=['POST'])
@exception_catch
def user_create():
    """
    增加用户
    入参参考数据库模型
    :return:
    """
    data = request.data.decode()
    try:
        params = json.loads(data)
        # params = request.get_json()
    except Exception as e:
        return jsonify({'code': 4000, 'data': [], "count": 0, "message": "fail", "error": "参数格式错误,请传json格式."})

    if db.session.query(User).filter_by(name=params.get("name")).first():
        return jsonify({'code': 4000, 'data': [], "count": 0, "message": "fail", "error": "该名称已存在."})
    try:
        user = User(**params)
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        print(str(e))
        return jsonify({'code': 5000, 'data': [], "count": 0, "message": "fail", "error": "创建失败."})
    return jsonify({'code': 0, 'data': [], "count": 0, "message": "success", "error": ""})


@user.route('/delete', methods=['POST', 'GET'])
@exception_catch
def user_delete():
    data = request.data.decode()
    params = json.loads(data)
    ids = params.get('ids')
    if not ids:
        return jsonify({'code': 4000, 'data': [], 'error': '请传入ids'})
    db.session.query(User).filter(User.id.in_(ids)).delete(synchronize_session=False)
    db.session.commit()
    return jsonify({'code': 0})


@user.route('/update', methods=['POST'])
@exception_catch
def user_update():
    data = request.data.decode()
    params = json.loads(data)
    _id = params.get('id')
    if not _id:
        return jsonify({'code': 4000, 'data': [], 'error': 'without user id!'})
    params.pop('id')
    db.session.query(User).filter(User.id == id).update(params)
    db.session.commit()
    return jsonify({'code': 0, 'data': [], 'message': '', 'error': ''})


@user.route('/list', methods=['GET'])
@exception_catch
def user_list():
    page = request.args.get('page', 1)
    size = request.args.get('size', 20)
    order = request.args.get("order", "id")

    try:
        page, size = int(page), int(size)
    except:
        return jsonify({'code': 0, 'data': [], 'message': 'failed', 'error': 'wrong params!'})

    queryset = db.session.query(User)
    queryset = queryset.order_by(order)[(page - 1) * size:page * size]
    item_list = [item._to_dict() for item in queryset]

    return jsonify({'code': 0, 'data': item_list, 'message': 'success', 'error': ''})
